package com.luo.demo.multi.ds.pkg.config;

import com.luo.demo.multi.ds.pkg.mapper.ds2.MyDataMapper2;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
/**
 * 数据源2 - 配置
 * 注：默认仅@Primary主数据源支持事务@Transactional，当前非主数据源不支持事务
 * @author luohq
 * @date 2022-08-06
 */
@Configuration
//注意此处需扫描对应数据源包下的mapper接口，且sqlSessionFactory为当前类中定义的SqlSessionFactory
@MapperScan(basePackageClasses = {MyDataMapper2.class}, sqlSessionFactoryRef = "ds2SqlSessionFactory")
public class DataSourceConfig2 {

    @Bean("ds2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.ds2")
    public DataSource ds2DataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean("ds2SqlSessionFactory")
    public SqlSessionFactory ds2SqlSessionFactory(@Qualifier("ds2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/ds2/*.xml"));
        return bean.getObject();
    }

    @Bean("ds2SqlSessionTemplate")
    public SqlSessionTemplate ds2SqlSessionTemplate(@Qualifier("ds2SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
